package com.exercises;

import com.arithmetic.BubbleSort;


import java.util.Arrays;

public class BubbleSortTest {
    public static void main(String[] args) throws Exception {
        BubbleSort bubbleSort = new BubbleSort();
        int arr[] = {1,2,3,412,222,52,908,92,1,42};
        int[] sort = bubbleSort.sort(arr);
        System.out.println("排序后的数组为：" + Arrays.toString(sort));
    }
    public int[] sort(int[] sourceArray) throws Exception {
        for (int i = 1; i < sourceArray.length; i++){ // 外层是循环次数
            boolean flag = true;
            for (int j = 0;j < sourceArray.length - i - 1; j++){ // 内层是循环比较
                if (sourceArray[j] > sourceArray[j + 1]){
                    int temp = sourceArray[j];
                    sourceArray[j] = sourceArray[j + 1];
                    sourceArray[j + 1] = temp;
                    flag = false;
                }
            }
            if (flag){ // 如果没有发生交换，且跳出循环则说明数组已经有序了
               break;
            }
        }
        return sourceArray;
    }
}
